﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmashedApples.Core;
using System.Data.SqlClient;
using SmashedApples.Data.Commands;
using SmashedApples.Data.Responses;
using SmashedApples.Data.Contexts;
using System.Collections;
using System.Data;

namespace SmashedApples.Data
{
    public static class SqlServer
    {
        public static SelectResponse select(SelectCommand cmd)
        {
            SelectContext context = new SelectContext(cmd);

            context = CommandBuilder.buildSelectCommand(context);

            SqlDataAdapter sqlAdapter = new SqlDataAdapter();
            sqlAdapter.SelectCommand = context.sqlCommand;
            sqlAdapter.Fill(context.response.data);

            return context.response;
        }

    
        public static ValueObject selectRowByPk(String table, String pk, Object value)
        {
            Hashtable data = new Hashtable();
            data.Add(pk, value);
            SelectResponse response = SqlServer.select(new SelectCommand(table, data));
            return new ValueObject(response.data);
        }

        public static SaveResponse save(SaveCommand cmd)
        {
            if (cmd.isInsert())
                return insert(cmd);
            return update(cmd);
        }

        public static SaveResponse insert(SaveCommand cmd)
        {
            SaveContext context = CommandBuilder.buildInsertCommand(new SaveContext(cmd));

            using (context)
            {
                context.sqlConnection.Open();
                Object pk = context.sqlCommand.ExecuteScalar();
                context.response.data = SqlServer.selectRowByPk(cmd.table, cmd.pk, pk);
            }

            return context.response;
        }
        public static SaveResponse update(SaveCommand cmd)
        {
            SaveContext context = CommandBuilder.buildUpdateCommand(new SaveContext(cmd));

            using (context)
            {
                context.sqlConnection.Open();
                context.sqlCommand.ExecuteScalar();
                context.response.data = SqlServer.selectRowByPk(cmd.table, cmd.pk,cmd.pkValue);
            }

            return context.response;
        }


        public static DeleteResponse delete(DeleteCommand cmd)
        {
            DeleteContext context = CommandBuilder.buildDeleteCommand(new DeleteContext(cmd));

            using (context)
            {
                context.sqlConnection.Open();
                context.sqlCommand.ExecuteScalar();
            }

            return context.response;
        }

    }
}
